package com.haima.sage.bigdata.api.process.impl;

import com.haima.sage.bigdata.api.common.Constants;
import com.haima.sage.bigdata.api.common.DbUtils;
import com.haima.sage.bigdata.api.common.EsUtils;
import com.haima.sage.bigdata.api.entity.storage.Storage;
import com.haima.sage.bigdata.api.exception.ValidateException;
import com.haima.sage.bigdata.api.process.ParamProcess;
import com.haima.sage.bigdata.api.vo.param.ColumnParam;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.util.LinkedList;
import java.util.List;

public class ColumnParamProcess extends ParamProcess {
    private static final Logger LOG = LogManager.getLogger(ColumnParamProcess.class);
    private ColumnParam param;
    EsUtils esUtils ;
    public ColumnParamProcess(ColumnParam param) {
        this.param = param;
    }

    protected Object executeES(Storage storage, String table, Integer maxBatchSize) {
        String entity = genEsJson(table,maxBatchSize);
        Object obj = null;
        try {
          //  obj = esUtils.esPost(storage, table, maxBatchSize, entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    protected Object executeRedis(Storage storage, String table, Integer maxBatchSize) {
        return null;
    }

    @Override
    public void validate() throws ValidateException {
        super.validate(param);
        validateField(param.getField());
    }

    private void validateField(String field) throws ValidateException {
        if (StringUtils.isEmpty(field)) {
            throw new ValidateException("field must not empty",
                    "field不能为空");
        }
        if (!Constants.fieldPattern.matcher(field).matches()) {
            throw new ValidateException("field must match regex: " + Constants.fieldPattern.pattern(),
                    "field必须匹配正则：" + Constants.fieldPattern.pattern());
        }
    }

    protected Object executeDB(Storage storage, String table, Integer maxBatchSize) throws Exception {
        String sql = genSQL(table);
        try (Connection conn = DbUtils.getConnection(storage.getId())) {
            return DbUtils.getColumnResult(sql, conn);
        }
    }

    /**
     * select ${field} from ${table}
     * where ${where}
     * @param table
     */
    private String genSQL(String table) throws ValidateException {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ");
        sql.append(param.getField());
        sql.append(" FROM ").append(table);
        // where
        appendWhere(sql, param.getWhere());
        return sql.toString();
    }

    /**
     * select ${field} from ${table}
     * where ${where}
     * @param table
     */
    private String genEsJson(String table, Integer maxBatchSize){
        esUtils = new EsUtils();
        StringBuilder jsonBody = new StringBuilder();
        jsonBody.append("{");
        //_source 字段
        List list = new LinkedList<String>();
        list.add(param.getField());
        esUtils.appendField(jsonBody,list);

        //query
        if(param.getWhere() != null) {
            jsonBody.append("\"query\":");
           // esUtils.appendWhere(jsonBody,param.getWhere());
        }

        jsonBody.append("\"size\": 10,");

        jsonBody.deleteCharAt(jsonBody.length() - 1);
        jsonBody.append("}");
        LOG.info(jsonBody.toString());
        return jsonBody.toString();
    }

}
